import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Comment } from './entities/comment.entity';
import { CreateCommentDto } from './dto/create-comment.dto';
import { QueryCommentDto } from './dto/query-comment.dto';
import { Goods } from './entities/goods.entity';
import { Order } from '../order/entities/order.entity';

@Injectable()
export class CommentService {
  @InjectRepository(Comment)
  private commentRepository: Repository<Comment>;

  @InjectRepository(Goods)
  private goodsRepository: Repository<Goods>;

  @InjectRepository(Order)
  private orderRepository: Repository<Order>;

  async create(createCommentDto: CreateCommentDto, userId: number) {
    const { content, rating, images, goodsId } = createCommentDto;

    // 检查商品是否存在
    const goods = await this.goodsRepository.findOne({
      where: { id: goodsId },
    });

    if (!goods) {
      throw new HttpException('商品不存在', HttpStatus.BAD_REQUEST);
    }

    // 检查是否已购买商品
    const order = await this.orderRepository.findOne({
      where: {
        goods: { id: goodsId },
        buyer: { id: userId },
        status: 4, // 已完成
      },
    });

    if (!order) {
      throw new HttpException('只能评论已购买的商品', HttpStatus.BAD_REQUEST);
    }

    // 检查是否已评论
    const existComment = await this.commentRepository.findOne({
      where: {
        goods: { id: goodsId },
        user: { id: userId },
      },
    });

    if (existComment) {
      throw new HttpException('已经评论过了', HttpStatus.BAD_REQUEST);
    }

    const comment = new Comment();
    comment.content = content;
    comment.rating = rating;
    comment.images = images;
    comment.goods = goods;
    comment.user = { id: userId } as any;

    try {
      await this.commentRepository.save(comment);
      return '评论成功';
    } catch (e) {
      throw new HttpException('评论失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async findAll(queryCommentDto: QueryCommentDto) {
    const { pageNum = 1, pageSize = 10, goodsId, userId } = queryCommentDto;

    const skipCount = (pageNum - 1) * pageSize;
    const condition: Record<string, any> = {};

    if (goodsId) {
      condition.goods = { id: goodsId };
    }
    if (userId) {
      condition.user = { id: userId };
    }

    const [comments, total] = await this.commentRepository.findAndCount({
      where: condition,
      skip: skipCount,
      take: pageSize,
      relations: ['user', 'goods'],
      order: {
        createTime: 'DESC',
      },
    });

    return {
      comments,
      total,
    };
  }
}
